package com.xuyuan.thread.stop;

public class ThreadInterruptExample {
    public static void main(String[] args) {
        CountThread countThread = new CountThread();
        countThread.start();
        // 主线程挂起一段时间，利用interrupt机制终止计数线程
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        countThread.interrupt();
    }

    /**
     * 计数线程
     */
    static class CountThread extends Thread {
        @Override
        public void run() {
            try {
                for (int i = 1; i <= 10; i++) {
                    // 检查当前线程的中断状态，如果线程状态中断，终止线程的执行
                    if (Thread.interrupted()) {
                        System.out.println("Count thread interrupted. Exiting...");
                        return;
                    }
                    System.out.println("Count: " + i);
                    Thread.sleep(1000);

                }
            } catch (InterruptedException e) {
                System.out.println("Count thread interrupted while sleeping. Exiting...");
                Thread.currentThread().interrupt();
            }
        }
    }
}
